import { Table, Button, Space, Popconfirm, message } from 'antd';
import { useState, useEffect } from 'react'
import { useStore } from '@/store'
import { columns } from '@/static/columns';
import { EditOutlined, DeleteOutlined, EllipsisOutlined, AppstoreAddOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import uuid from 'react-uuid'


function SimpleTableComponent(props) {
    const {api, requetParams} = props
    const navigate = useNavigate()

    const [params, setParams] = useState({
        current: 1,
        pageSize: 10
    })

    const [data, setData] = useState({
        list: [],
        total: 0,
        loading: false
    })

    // 组件渲染
    const { operateStore } = useStore()
    useEffect(() => {
        async function fetchList() {
            setData({loading: true})
            if(params.sort===undefined || params.sort === "-undefined"){
                params["sort"] = "-id"
            }
            const data = await operateStore.getItems(api, params)
            setData({
                list: data.list,
                total: data.total,
                loading: false
            })
        }
        fetchList()
       
    }, [operateStore, api, params])

    // 条件查询
    useEffect(()=>{
        if(undefined !== requetParams){
            setParams({
                ...requetParams
            })
        }else{
            setParams({
                current: 1,
                pageSize: 10
            })
        }
    }, [requetParams])

    //分页、筛选、排序
    const handleTableChange = async(pagination, filters, sorter) => {
        setParams({
            ...params,
            current: pagination.current,
            sort: sorter.order === "descend" ? sorter.field  : "-".concat(sorter.field ) 
        })
    }

    const [visible, setVisible] = useState(false);
    const [id, setId] = useState(0);
    const [confirmLoading, setConfirmLoading] = useState(false);
  
    const showPopconfirm = (id) => {
      setId(id);
      setVisible(true);
    };
  
    const handleOk = async(id) => {
      setConfirmLoading(true);
      await operateStore.deleteItem(api, id)
      setParams({
        ...params,
        current: 1
      })
      setConfirmLoading(false);
      message.success('This is a success message');
    };
  
    const handleCancel = () => {
      setVisible(false);
    };

    const operateClick = (id) => {
        navigate(`/operate/${api}?id=${id}&api=${api}`)
    }

    const detailsClick = (id) => {
        navigate(`/details/${api}?id=${id}&api=${api}`)
    }

    const addClick = () => {
        navigate(`/operate/${api}?api=${api}`)
    }

    let column  = []
    if( api === "student_score" ){
        column = columns[api] ? columns[api] : []
    }else{
        column = columns[api] ? columns[api].concat({
            title: '操作',
            render: record => {
            if(api === "exam_paper"){
                return (
                    <Space size="middle">
                    <Popconfirm
                        title="确定要删除吗？"
                        okText="确定"
                        cancelText="取消"
                        visible={visible && record.id === id }
                        onConfirm={(e) => handleOk(record.id)}
                        okButtonProps={{ loading: confirmLoading }}
                        onCancel={handleCancel}
                        >
                        <Button type="primary" danger  shape="circle" icon={<DeleteOutlined />} onClick={()=>showPopconfirm(record.id)} />
                    </Popconfirm>
                    <Button type="primary" shape="circle" icon={<EllipsisOutlined />} onClick={()=>detailsClick(record.id)} />
                    </Space>
                )  
            }else if(api === "mark_papers"){
                return (
                    <Space size="middle">
                        <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={()=>operateClick(record.id)} />
                    </Space>
                )  
            }else{
                return (
                    <Space size="middle">
                    <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={()=>operateClick(record.id)} />
                    <Popconfirm
                        title="确定要删除吗？"
                        okText="确定"
                        cancelText="取消"
                        visible={visible && record.id === id }
                        onConfirm={(e) => handleOk(record.id)}
                        okButtonProps={{ loading: confirmLoading }}
                        onCancel={handleCancel}
                        >
                        <Button type="primary" danger  shape="circle" icon={<DeleteOutlined />} onClick={()=>showPopconfirm(record.id)} />
                    </Popconfirm>
                    <Button type="primary" shape="circle" icon={<EllipsisOutlined />} onClick={()=>detailsClick(record.id)} />
                    </Space>
                )
            }
            }
        }) : []
    }

    return (
        <>
            {column && column.length > 0 && (
            <>
                <div style={{textAlign:"right", marginBottom: "20px"}}>
                   {api!== "mark_papers" && api !== "student_score" ? <Button type='primary' icon={<AppstoreAddOutlined />} onClick={addClick}>新增</Button> : undefined}
                </div>
                <Table
                    columns={column}
                    rowKey={uuid}
                    dataSource={data.list}
                    pagination = {
                        {
                        pageSize: params.pageSize,
                        total: data.total,
                        current: params.current,
                        showTotal: (total, range) => `${range[0]}-${range[1]} 条/ 共 ${total} 条`
                        }
                    }
                    loading={data.loading}
                    onChange={handleTableChange}
                />
            </>
            )}
        </>
    )
}

export default SimpleTableComponent;